#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <assert.h>
#include <string.h>

#define CLEAN_CHAR(pos, buf, delim)	do {\
										pos = (char*)buf;\
										while (pos && *pos) {\
											if (*pos == delim) {\
												*pos = '\0';\
												break;\
											}\
											pos++;\
										}\
									}while (0)\

#define CLEAN_CHAR_R(pos, buf, delim)	do {\
											pos = (char*)buf + strlen(buf) - 1;\
											while (pos >= buf && *pos) {\
												if (*pos == delim) {\
													*pos = '\0';\
													break;\
											}\
											pos--;\
										}\
}										while (0)\

size_t get_file_size(const char *path)
{
	struct stat st;
	bzero(&st, sizeof(struct stat));
	stat(path, &st);
	return st.st_size;
}

int __get_cfg_value(const char *path, const char *section,
				char *name, char *value, size_t value_size)
{
	FILE *fp = NULL;
	char section_flag = 0;
	size_t size;
	int ret = 0;
	char *buf = NULL;
	char *pos = NULL;

	if ( (size = get_file_size(path) ) == 0)
		return 0;

	if ( (fp = fopen(path, "r")) == NULL)
		return 0;

	if ( (buf = calloc(1, size)) == NULL)
		return 0;
	
	bzero(value, value_size);

	while (fgets(buf, size, fp) != NULL) {

		if (section_flag) {
			if (!strncasecmp(buf, name, strlen(name)))	{
				CLEAN_CHAR_R(pos, buf, ';');
				strtok_r(buf, " =", &pos);
				if (pos) {
				   	ret = strlen(pos);
					if (ret <= value_size)
						memcpy(value, pos, strlen(pos));
					else
						ret = 0;
					break;
				}
			}	
		}

		if (!strncasecmp(buf, section, strlen(section))) {
			section_flag = 1;
			continue;
		}
	}

	free(buf);
	fclose(fp);
	return ret;
}

int get_cfg_value(const char *path, const char *section, 
				char *name, char *value, size_t value_size)
{
	assert(path && section && name && value);

	char sec[1024] = {0};
	snprintf(sec, 1024, "[%s]", section);
	return __get_cfg_value(path, sec, name, value, value_size);
}

int main(void)
{
	int ret = 0;
	int n, i;
	char value[1024] = {0};
	char name[64];

	if ( (ret = get_cfg_value("./custom.conf", "NETBIOS", "LIST_NUM", value, 1024)) == 0 ) {
		printf("get_cfg_value failed\n");
		return 0;
	}
	
	n = atoi(value);

	for (i = 0; i < n; i++) {
		sprintf(name, "LIST_INFO%d", i);

		if ( (ret = get_cfg_value("./custom.conf", "NETBIOS", name, value, 1024)) == 0 ) {
			printf("get %s failed\n", name);
			return 0;
		}
		
		printf("%s->%s\n", name, value);
	}
	
	return 0;
}
